<template>
  <div>
    <a-select 
      showSearch
      v-model="selectedValue"
      @change="handleChange"
      :placeholder="placeholder"
      :filterOption="filterOption"
      allowClear
      :size="size"
      @blur="handleBlur"
      ref="select"
    >
      <a-select-option v-for="item in data" :key="item.id">{{item.userName}}</a-select-option>
    </a-select>
  </div>
</template>
<script>
import axios from 'axios'

export default {
  mounted() {
    // load data for case of modify form display label, otherwise will display key
    this.fetch()
  },
  watch:{
    value: function() {
      this.selectedValue = this.value
    }
  },
  props: {
    value: { type: [String] },
    desc: { type: [String], default:''},
    resourceId: { type: [String] },
    roleCodes: { type: [String] }, // comma separator
    isActive: { type: [Boolean], default: false },
    placeholder: { type: [String], default:''},
    size: { type: [String], default: 'default' },
    appendOptions: { type: [Array], default: () => { return [] } },
  },
  data() {
    return {
      selectedValue: this.value,
      data: this.value ? [{id: this.value, userName: this.desc}] : [],
    }
  },
  methods: {
    fetch () {
      axios({
        url: '/infra/user/getPendingUser',
        method: 'get',
        params: {resourceId: this.resourceId, roleCodes: this.roleCodes, isActive: this.isActive},
      }).then((res) => {
        this.data = [...res.data.rows, ...this.appendOptions]
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleChange(val) {
      // Should provide an event to pass value to Form.
      let result = this.data.filter(item => {
        return item.id == val
      })
      let row = {}
      if (result.length > 0) {
        row = result[0]
      }
      this.$emit('change', val, row)
    },
    handleBlur(e) {
      this.$emit('blur', e)
    },
    focus() {
      this.$nextTick(function() {
        this.$refs.select.focus()
      })
    },
  }
}
</script>
